/**
 * Created by on 2016/7/10.
 */
 
var redis = require('redis');
var co = require('co');


class redisMasterModel{

	constructor(){

		this.client={};

	}

	createClient(obj){
		
		this.client=redis.createClient(obj);

	}

	getArticleIdArr(id){
		return new Promise((resolve,reject)=>{
			if (id==0)id=Date.now()
			this.client.zrevrangebyscore('aritleContextId',id,0,(err,res)=>{
				if (err) reject(err)
				resolve(res)
			})
		})
	}

	getArticleInfor(id){
		return new Promise((resolve,reject)=>{
			this.client.hget('aritleContext',id,(err,res)=>{
				if (err) reject(err)
				var res = JSON.parse(res)
				this.getUsersInfor(res.creater)
						.then(result=>{
							res.user=result
							resolve(res)	
						})
						.catch(err=>{
							console.log(err);
							reject(err)
						})
			})
		})
	}

	getCommentsInfor(idArr){
		return new Promise((resolve,reject)=>{
			let comIdArr=[]
			idArr.split().map(r=>comIdArr.push(this.getCommentsInforUser(r)))
			Promise.all(comIdArr)
				   .then(result=>resolve(result))
				   .catch(err=>reject(err))
		})
	}

	getCommentsInforUser(id){
		console.log('************************');
		console.log(id);
		console.log('************************');
		return new Promise((resolve,reject)=>{
			this.client.hget('comments',id,(err,res)=>{
				if (err) reject(err)
				var res = JSON.parse(res)
				this.getUsersInfor(res.creater)
					.then(result=>{
						res.user=result
						resolve(res)
					})
					.catch(err=>{
						console.log(err);
						reject(err)
					})
			})
		})
	}

	getArticleCount(){
		return new Promise((resolve,reject)=>{
			this.client.zlexcount('aritleContextId','-','+',(err,res)=>{
				if (err) {
					console.log(err);
					reject(err)
				}
				resolve(JSON.parse(res))
			})
		})
	}

	getUsersInfor(id){
		return new Promise((resolve,reject)=>{
			this.client.hget('users',id,(err,res)=>{
				if (err) {
					console.log(err);
					reject(err)
				}
				resolve(JSON.parse(res))
			})
		})
	}

	

}

module.exports = new redisMasterModel();
